package com.nowcoder.community.service;

import com.nowcoder.community.dao.CommentMapper;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService implements CommunityConstant {

    @Autowired
    private DiscussPostMapper discussPostMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private CommentMapper commentMapper;

    //分页查询
    public  List<Comment> findCommentsByEntity(int entityType,int entityId,int offset, int limit){
        return commentMapper.selectCommentByEntity(entityType,entityId,offset,limit);
    }
    //查询总条数
    public  int  findCommentCount(int entityType,int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }

    /**
     * 新增评论
     */
    //因为该方法包括两次Dao操作，所以进行事务管理，保证两个操作在一个事务管理之内，要么都成功，要么都失败
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        //空值异常处理
        if(comment == null){
            throw new IllegalArgumentException("参数不能为空!");
        }
        //添加评论
            //传入实体，内容过滤，包括html标签的过滤，敏感词的过滤,其中内容过滤实质为重新赋值
                //过滤html标签,使用HtmlUtils.htmlEscape()方法
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
                 //过滤敏感词
                 //因为要使用敏感词过滤，注入对应的bean对象
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);

        //更新评论数量：只有新增帖子评论的时候，才更新评论数量，新增评论的评论不更新
            //使用常量先继承接口
        if(comment.getEntityType()== ENTITY_TYPE_POST){
            //更新评论数量，先得到评论的数量
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            //更新到帖子表里
            discussPostMapper.updateCommentCount(comment.getEntityId(),count);

        }

        return rows;

    }

}
